package com.growthsee.framework.security.handle;

import cn.hutool.json.JSONUtil;
import com.growthsee.common.core.domain.AjaxResult;
import com.growthsee.common.core.domain.model.LoginUser;
import com.growthsee.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private TokenService tokenService;
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("登录成功");
        /** 组装 josn 返回 前端*/
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String token = tokenService.createToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put("access_token",token);
        claims.put("authentication",authentication);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSONUtil.toJsonStr(AjaxResult.success("成功",token)));
    }
    }
